import os
import subprocess


class ADB:
    def __init__(self):
        # 初始化时检测是否可以连接设备
        self.check_device()

    def check_device(self):
        """检查设备是否连接"""

        result = subprocess.run(['adb', 'connect', '127.0.0.1:7555'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        result = subprocess.run(['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if b'device' not in result.stdout:
            raise Exception("No devices connected")
        print("Device connected.")

    def click(self, x, y):
        """根据坐标点击"""
        command = f"adb shell input tap {x} {y}"
        result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            pass
            # print(f"Clicked at ({x}, {y})")
        else:
            print(f"Failed to click at ({x}, {y})")
            print(result.stderr.decode())

    def take_screenshot(output_path="png.jpg"):
        """
        使用 ADB 截取模拟器屏幕并保存为图片
        :param output_path: 截图保存路径，默认为 png.jpg
        """
        subprocess.run(['adb', 'shell', 'screencap', '-p', '/sdcard/png.jpg'])
        # 从设备获取截图
        subprocess.run(['adb', 'pull', '/sdcard/png.jpg', './png.jpg'])
        # 删除设备上的截图文件
        subprocess.run(['adb', 'shell', 'rm', '/sdcard/png.jpg'])
        print("Screenshot saved as png.jpg")


if __name__ == '__main__':
    ADB().take_screenshot()
